package com.atguigu.tingshu.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.client.AlbumInfoFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.order.OrderDerate;
import com.atguigu.tingshu.model.order.OrderDetail;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.user.VipServiceConfig;
import com.atguigu.tingshu.order.helper.SignHelper;
import com.atguigu.tingshu.order.mapper.OrderInfoMapper;
import com.atguigu.tingshu.order.service.OrderInfoService;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.atguigu.tingshu.user.client.VipServiceConfigFeignClient;
import com.atguigu.tingshu.vo.order.OrderDerateVo;
import com.atguigu.tingshu.vo.order.OrderDetailVo;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import com.atguigu.tingshu.vo.order.TradeVo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private UserInfoFeignClient userInfoFeignClient;

    @Autowired
    private AlbumInfoFeignClient albumInfoFeignClient;

    @Autowired
    private VipServiceConfigFeignClient vipServiceConfigFeignClient;

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public OrderInfoVo trade(TradeVo tradeVo, Long userId) {
        //创建订单信息对象
        OrderInfoVo orderInfoVo = new OrderInfoVo();
        //初始化数据
        BigDecimal originalAmount = new BigDecimal("0.00");
        BigDecimal derateAmount = new BigDecimal("0.00");
        BigDecimal orderAmount = new BigDecimal("0.00");
        List<OrderDetailVo> orderDetailVoList = new ArrayList<>();
        List<OrderDerateVo> orderDerateVoList = new ArrayList<>();

        //判断用户购买的类型  itemtype：专辑、vip、声音
        if (tradeVo.getItemType().equals(SystemConstant.ORDER_ITEM_TYPE_ALBUM)) {
            //用户购买的专辑
            //根据传进来的readeVo拿到当前的专辑id
            Long albumId = tradeVo.getItemId();
            //根据专辑id，远程调用看用户是否买过当前专辑
            Result<Boolean> isPaidAlbumResult = userInfoFeignClient.isPaidAlbum(albumId);
            if (isPaidAlbumResult.getData()) {
                //有数据，说明购买过，
                throw new GuiguException(ResultCodeEnum.REPEAT_BUY_ERROR);
            }
            //没有数据我们要通过远程调用拿到专辑信息
            Result<AlbumInfo> albumInfoResult = albumInfoFeignClient.getAlbumInfo(albumId);
            Assert.notNull(albumInfoResult, "专辑信息结果集为空");
            //获取到专辑信息。获取到当前专辑下的价格
            AlbumInfo albumInfo = albumInfoResult.getData();
            //将专辑的价格赋值给订单下这个专辑的原始价格
            originalAmount = albumInfo.getPrice();
            //接下来看这个专辑对应的折扣，首先要看当前用户是否是vip
            //远程调用user模块
            //这里的id不是albumInfo.getUserId(),而是当前登录对象userId
            Result<UserInfoVo> userInfoVoResult = userInfoFeignClient.getUserInfoVoByUserId(userId);
            Assert.notNull(userInfoVoResult, "userInfoVoResult为空");
            UserInfoVo userInfoVo = userInfoVoResult.getData();
            if (userInfoVo.getIsVip() == 1 && userInfoVo.getVipExpireTime().after(new Date())) {
                //当前用户是vip且没有过期,就要打折扣
                //判断当前专辑信息是否有折扣
                //compareTo底层:  return 前数据 != 后数据 ? ((前数据 > 后数据) ? 1 : -1) : 0;
                if (albumInfo.getVipDiscount().compareTo(new BigDecimal("-1")) == 1) {
                    //说明当前专辑有折扣
                    //减免金额
                    derateAmount = originalAmount.multiply(albumInfo.getVipDiscount().divide(new BigDecimal("10")));
                }
            } else {
                //不是vip,则走普通折扣
                if (albumInfo.getDiscount().compareTo(new BigDecimal("-1")) == 1) {
                    //说明有折扣

                    //减免金额
                    derateAmount = originalAmount.multiply(albumInfo.getDiscount().divide(new BigDecimal("10")));
                }
            }
            //订单总价格
            orderAmount = originalAmount.add(derateAmount);
            //创建订单明细对象
            OrderDetailVo orderDetailVo = new OrderDetailVo();
            orderDetailVo.setItemId(albumId);
            orderDetailVo.setItemName(albumInfo.getAlbumTitle());
            orderDetailVo.setItemPrice(orderAmount);
            orderDetailVo.setItemUrl(albumInfo.getCoverUrl());
            orderDetailVoList.add(orderDetailVo);

            //减免金额有，才会进行生成对象
            //判断建模金额是不是有，也就是大于1
            if (derateAmount.compareTo(new BigDecimal("0")) == 1) {
                //创建减免明细对象
                OrderDerateVo orderDerateVo = new OrderDerateVo();
                orderDerateVo.setRemarks("专辑折扣");
                orderDerateVo.setDerateType(tradeVo.getItemType());
                orderDerateVo.setDerateAmount(derateAmount);
                orderDerateVoList.add(orderDerateVo);
            }

        } else if (tradeVo.getItemType().equals(SystemConstant.ORDER_ITEM_TYPE_VIP)) {
            //购买的是vip
            //根据id获取到vip配置信息vip_service_config
            Long vipServiceConfigId = tradeVo.getItemId();
            //远程调用user模块
            Result<VipServiceConfig> vipServiceConfigResult = vipServiceConfigFeignClient.getVipServiceConfig(vipServiceConfigId);
            VipServiceConfig vipServiceConfig=vipServiceConfigResult.getData();
            //原始金额
            originalAmount = vipServiceConfig.getPrice();
            //订单总价格
            orderAmount =vipServiceConfig.getDiscountPrice();
            //减免价格
            derateAmount=originalAmount.subtract(orderAmount);

            OrderDetailVo orderDetailVo = new OrderDetailVo();
            orderDetailVo.setItemUrl(vipServiceConfig.getImageUrl());
            orderDetailVo.setItemId(vipServiceConfigId);
            orderDetailVo.setItemPrice(originalAmount);
            orderDetailVo.setItemName(vipServiceConfig.getName());
            orderDetailVoList.add(orderDetailVo);

            if(derateAmount.compareTo(new BigDecimal("0"))==1){
                OrderDerateVo orderDerateVo = new OrderDerateVo();
                orderDerateVo.setDerateAmount(derateAmount);
                orderDerateVo.setRemarks("VIP折扣");
                orderDerateVo.setDerateType(tradeVo.getItemType());
            }
        } else {
            //ORDER_ITEM_TYPE_TRACK
            //用户购买的是声音

        }
        //定义一个交易流水号
        String tradeNo= UUID.randomUUID().toString().replaceAll("-","");
        //定义一个key，
        String tradeNoKey="tradeNo:"+userId;
        //订单过期时间设置为10分钟，并且上锁
        redisTemplate.opsForValue().setIfAbsent(tradeNoKey,tradeNo,10, TimeUnit.MINUTES);

        //封装数据
        orderInfoVo.setTradeNo(tradeNo);
        orderInfoVo.setPayWay("");
        orderInfoVo.setItemType(tradeVo.getItemType());
        orderInfoVo.setOriginalAmount(originalAmount);
        orderInfoVo.setDerateAmount(derateAmount);
        orderInfoVo.setOrderAmount(orderAmount);
        orderInfoVo.setOrderDetailVoList(orderDetailVoList);
        orderInfoVo.setOrderDerateVoList(orderDerateVoList);
        orderInfoVo.setTimestamp(SignHelper.getTimestamp());

        Map map = JSON.parseObject(JSON.toJSONString(orderInfoVo), Map.class);
        String sign = SignHelper.getSign(map);

        orderInfoVo.setSign(sign);

        return orderInfoVo;
    }
}
